package cn.seapon.talker.net;

import java.io.File;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;

/** 
 * @author 作者 E-mail: 
 * @version 创建时间：2015年1月4日 下午7:59:49 
 * 类说明 
 */
public class DownloadUtils {


	/**
	 * 下载并安装APK
	 * @param context  上下文
	 * @param downloadUrl  下载地址
	 * @param localName 保存到本地的名字
	 */
	 public static void downloadToInstallApk(final Context context,String downloadUrl,String localName){
		//下载APK，并且替换安装
		if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
			//如果sdcard存在
			//afnal
			FinalHttp finalhttp = new FinalHttp();
			finalhttp.download(downloadUrl,Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+localName, 
					new AjaxCallBack<File>() {
						@Override
						public void onFailure(Throwable t, int errorNo,
								String strMsg) {
							t.printStackTrace();
							Toast.makeText(context,"下载失败",Toast.LENGTH_SHORT).show();
							super.onFailure(t, errorNo, strMsg);
						}
						@Override
						public void onLoading(long count, long current) {
							super.onLoading(count, current);
							//当前下载百分比
							int progress = (int) (current * 100/count);
							//使用广播通知
							Intent intent = new Intent();
							intent.putExtra("current_progress", progress);
							intent.setAction("cn.seapon.talker.SHOW_DOWNLOAD_PROGRESS");// action与接收器相同
							context.sendBroadcast(intent);
						}
						@Override
						public void onSuccess(File t) {
							super.onSuccess(t);
							installAPK(t);
						}
						//安装APK
						private void installAPK(File t) {
							Intent intent = new Intent();
							intent.setAction("android.intent.action.VIEW");
							intent.addCategory("android.intent.category.DEFAULT");
							intent.setDataAndType(Uri.fromFile(t),"application/vnd.android.package-archive");
							context.startActivity(intent);
						}
					});
		}else{
			Toast.makeText(context,"没有sdcard,请安装上在试",Toast.LENGTH_SHORT).show();
		}
	}
	

}
